package ar.posti.framework.query.core.paginator;

import java.util.ArrayList;
import java.util.List;

import ar.posti.framework.query.Query;

public class QueryPaginator {
	private Query query;

	public QueryPaginator() {}
	public QueryPaginator(Query query) {
		this.query = query;
	}

	public void setQuery(Query query) {
		this.query = query;
	}

	public Page findPage(int pageNumber, int itemsPerPage) {
		List results;
		int totalPages = (int) Math.ceil((double) query.count() / itemsPerPage);
		pageNumber = Math.min(pageNumber, totalPages - 1);
		
		if (totalPages == 0)
			results = new ArrayList();
		else {
			int firstElement = itemsPerPage * (pageNumber - 1) + 1;
			int lastElement = itemsPerPage * pageNumber;
			results = query.list(new Integer(firstElement), new Integer(lastElement));
		}

		return this.buildPage(results, pageNumber, totalPages);
	}
	private Page buildPage(List results, int pageNumber, int totalPages) {
		Page page = new Page();
		page.setCurrentPage(pageNumber);
		page.setTotalPages(totalPages);
		page.setResults(results);
		return page;
	}
}
